package cn.study.aviplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

import java.util.concurrent.atomic.AtomicBoolean;

public class NativeWindowPlayerActivity extends AbstractPlayerActivity {

    private final AtomicBoolean isPlaying = new AtomicBoolean();

    private SurfaceHolder surfaceHolder;
    SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_native_window_player);

        surfaceView = findViewById(R.id.surface_view);

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(callback);
    }

    @Override
    protected void onStart() {
        super.onStart();

        int w = getWidth(avi);
        int h = getHeight(avi);

        //设置surfaceView的带大小，防止自动填充
        ViewGroup.LayoutParams viewGroup = surfaceView.getLayoutParams();
        viewGroup.width = w;
        viewGroup.height = h;

        surfaceView.setX(50);
        surfaceView.setY(50);

    }

    private final SurfaceHolder.Callback callback = new SurfaceHolder.Callback2() {
        @Override
        public void surfaceRedrawNeeded(SurfaceHolder holder) {

        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {

            isPlaying.set(true);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            isPlaying.set(true);
            new Thread(renderer).start();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

            isPlaying.set(false);
        }
    };


    private Runnable renderer = new Runnable() {
        @Override
        public void run() {

            Surface surface = surfaceHolder.getSurface();

            init(avi, surface);

            long frameDelay = (long) (1000 / getFrameRate(avi));

            while (isPlaying.get()) {

                render(avi, surface);

                try {

                    Thread.sleep(frameDelay);
                } catch (InterruptedException e) {

                    break;
                }

            }
        }
    };


    /**
     * 初始化原生window
     *
     * @param avi
     * @param surface
     */
    private native static void init(long avi, Surface surface);

    /**
     * 渲染
     * @param avi
     * @param surface
     * @return
     */
    private native static boolean render(long avi, Surface surface);
}
